package cn.com.css.taxInspection.system.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itextpdf.io.IOException;

import cn.com.css.taxInspection.common.aop.annotation.LogAnnotation;
import cn.com.css.taxInspection.system.entity.SysLog;
import cn.com.css.taxInspection.common.result.DataResult;
import cn.com.css.taxInspection.gt3.entity.JcAjxxEntity;
import cn.com.css.taxInspection.system.service.LogService;
import cn.com.css.taxInspection.system.service.impl.HttpSessionService;
import cn.com.css.taxInspection.util.TsBqUtils;
import cn.com.css.taxInspection.workflow.entity.WorkflowLogEntity;
import cn.com.css.taxInspection.workflow.vo.excel.LogExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统操作日志
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@RequestMapping("/sys")
@Api(tags = "系统模块-系统操作日志管理")
@RestController
public class SysLogController {
    @Resource
    private LogService logService;
    @Resource
    private HttpSessionService httpSessionService;
    @Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@PostMapping("/logs")
    @ApiOperation(value = "分页查询系统操作日志接口")
    @LogAnnotation(title = "系统操作日志管理", action = "分页查询系统操作日志")
    @RequiresPermissions("sys:log:list")
    public DataResult pageInfo(@RequestBody SysLog vo) throws ParseException {
        
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    	Page page = new Page(vo.getPage(), vo.getLimit());
        LambdaQueryWrapper<SysLog> queryWrapper = Wrappers.lambdaQuery();
        if (!StringUtils.isEmpty(vo.getUsername()) ) {
            queryWrapper.like(SysLog::getUsername, vo.getUsername());
        }
        if (!StringUtils.isEmpty(vo.getOperation()) ) {
            queryWrapper.like(SysLog::getOperation, vo.getOperation());
        }
        if (!StringUtils.isEmpty(vo.getStartTime()) ) {
            
			queryWrapper.gt(SysLog::getCreateTime, sdf.parse(vo.getStartTime()));

        }
        if (!StringUtils.isEmpty(vo.getEndTime()) ) {
			queryWrapper.lt(SysLog::getCreateTime, sdf.parse(vo.getEndTime()));

        }
        
        if (!StringUtils.isEmpty(vo.getTaxorgcode()) ) {
            queryWrapper.like(SysLog::getTaxorgcode, vo.getTaxorgcode());
        }
        
        queryWrapper.orderByDesc(SysLog::getCreateTime);
        return DataResult.success(logService.page(page, queryWrapper));
    }

    @DeleteMapping("/logs")
    @ApiOperation(value = "删除日志接口")
    @LogAnnotation(title = "系统操作日志管理", action = "删除系统操作日志")
    @RequiresPermissions("sys:log:deleted")
    public DataResult deleted(@RequestBody List<String> logIds) {
        logService.removeByIds(logIds);
        return DataResult.success();
    }
    
    
    @PostMapping("/addLogs")
    @ApiOperation(value = "添加日志接口")
    public DataResult add(@RequestBody SysLog vo) {
        
    	vo.setUsername(httpSessionService.getCurrentUsername());
    	vo.setUserId(httpSessionService.getCurrentUsername());
    	
    	logService.save(vo);
        return DataResult.success();
    }
    
    
    @PostMapping("/exportData")
	@ResponseBody
    public DataResult exportData(@RequestBody SysLog vo) throws java.io.IOException, ParseException {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	
        LambdaQueryWrapper<SysLog> queryWrapper = Wrappers.lambdaQuery();
        if (!StringUtils.isEmpty(vo.getUsername()) ) {
            queryWrapper.like(SysLog::getUsername, vo.getUsername());
        }
        if (!StringUtils.isEmpty(vo.getOperation()) ) {
            queryWrapper.like(SysLog::getOperation, vo.getOperation());
        }
        
        /*if (!StringUtils.isEmpty(vo.getStartTime()) ) {
            queryWrapper.gt(SysLog::getCreateTime, vo.getStartTime());
        }
        if (!StringUtils.isEmpty(vo.getEndTime()) ) {
            queryWrapper.lt(SysLog::getCreateTime, vo.getEndTime());
        }*/
        
        if (!StringUtils.isEmpty(vo.getStartTime())) {
			queryWrapper.gt(SysLog::getCreateTime, sdf.parse(vo.getStartTime()));
		}
		if (!StringUtils.isEmpty(vo.getEndTime())) {
			queryWrapper.lt(SysLog::getCreateTime, sdf.parse(vo.getEndTime()));
		}
        
        
        if (!StringUtils.isEmpty(vo.getTaxorgcode()) ) {
            queryWrapper.like(SysLog::getTaxorgcode, vo.getTaxorgcode());
        }
        
        List<SysLog> logList = logService.list(queryWrapper);

		if (logList.size() > 0) {
			List<LogExcel> logExcelList = new ArrayList<>();
			for (SysLog log : logList) {

				LogExcel logExcel = LogExcel.builder()
						.username(log.getUsername())
						.operation(log.getOperation())
						.method(log.getMethod())
						.params(log.getParams())
						.taxorgcode(log.getTaxorgcode())
						.createTime(log.getCreateTime())
						.build();
				
				logExcelList.add(logExcel);

			}

			String fileName = TsBqUtils.getUUID() + ".xlsx";

			String excelPath = filePath + fileName;
			OutputStream out = null;

			try {
				out = new FileOutputStream(excelPath);
				ExcelWriter writer = EasyExcelFactory.getWriter(out);

				Sheet sheet1 = new Sheet(1, 0, LogExcel.class);
				sheet1.setSheetName("数据");
				writer.write(logExcelList, sheet1);
				// 将上下文中的最终 outputStream 写入到指定文件中
				writer.finish();
				File excelFile = new File(excelPath);
				List<Object> excelFileInfo = new ArrayList<>();
				excelFileInfo.add(fileName);
				excelFileInfo.add(excelFile.length());
				excelFileInfo.add(fileUrl + "/" + fileName);

				return DataResult.success(excelFileInfo);

			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return DataResult.fail("xlsx生成失败：" + e.toString());
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return DataResult.fail("xlsx生成失败：" + e.toString());
				}

			}

		} else {
			return DataResult.fail("传入的ids为null！");
		}
	}
    
    
}
